﻿// -----------------------------------------------------------------------
// <copyright file="Users.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Collections.Generic;
using BasicFrameworkDemo.IBLL;
using BasicFrameworkDemo.Utility;

namespace BasicFrameworkDemo.BLL
{
    using System;

    using BasicFrameworkDemo.IDAL;
    using BasicFrameworkDemo.Model;
    using System.Linq;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class Users : IUsers
    {
        private readonly IRepository<UsersEntity> usersRepository;

        public Users(IRepository<UsersEntity> usersRepository)
        {
            this.usersRepository = usersRepository;
        }

        public IList<UserResponse> GetUserInfo(UserRequest userRequest)
        {
            if (userRequest.IsNullOrEmpty())
            {
                return null;
            }

            var func = this.CreateSearchCondition(userRequest);

            var userList = usersRepository.EntityQueryable.Where(func);
            var userinfo = (from user in userList
                            select new UserResponse
                                {
                                    UserName = user.Name,
                                    Age = user.Age,
                                    Sex = user.Sex
                                }).ToList();

            return userinfo;
        }

        private Func<UsersEntity, bool> CreateSearchCondition(UserRequest userRequest)
        {
            Func<UsersEntity, bool> func = user =>
                {
                    bool result = true;
                    if (!userRequest.Name.IsNullOrEmpty())
                    {
                        result &= user.Name == userRequest.Name;
                    }
                    if (!userRequest.Sex.IsNullOrEmpty())
                    {
                        result &= user.Sex == userRequest.Sex;
                    }
                    if (!userRequest.MinAge.IsNullOrEmpty())
                    {
                        result &= user.Age >= userRequest.MinAge;
                    }
                    if (!userRequest.MaxAge.IsNullOrEmpty())
                    {
                        result &= user.Age < userRequest.MinAge;
                    }
                    return result;
                };
            return func;
        }
    }
}
